<template>
  <div class="content-wrapper">
    <mt-header fixed :title="username"></mt-header>
    <div class="content-wrapper-context">
      <div class="searchbox_bar">
        <div class="searchbox">
          <input
            type="search"
            id="searchContent"
            class="C_commonInput"
            placeholder="查找地点"
            maxlength="64"
          >
          <button type="submit" class="button" v-on:click="submit"></button>
        </div>
      </div>
      <div class="mycontrollocat" id="locatAvoid" v-on:click="addAvoid"></div>
      <div class="mycontrolclear" v-on:click="clearAvoid"></div>
      <div class="info" v-if="poiInfo.isShow">
        <div class="placeinfo">
          <span class="title">{{poiInfo.name}}</span>
          <span class="address">{{poiInfo.address}}</span>
          <span class="address" v-show="naviLine.isShow" id="promptinfo">{{naviLine.promptInfo}}</span>
        </div>
        <div class="bottombutton" v-on:click="search(myLocation,destination)">路线推荐</div>
      </div>
      <div id="AMapContainer"></div>
    </div>
  </div>
</template>

<script>
// Vue.component(Popup.name, Popup);
import { Popup } from "mint-ui";
import AMap from "AMap";
import destinationPng from "@/assets/images/destination.png";
import poimarker from "@/assets/images/marker.png";
import startPng from "@/assets/images/start.png";
import axios from "@/api/axios";
import { mapGetters } from "vuex";
import { Toast } from "mint-ui";
import { MessageBox } from "mint-ui";

export default {
  data: function() {
    return {
      username: null,
      map: null,
      id: null,
      myLocation: null,
      destination: {
        lng: null,
        lat: null
      },
      destinationMarker: null,
      avoidRoad: null,
      avoidPoint: null,
      avoidPointCircle: new Array(),
      overlays: new Array(), //规划路径
      poiInfo: {
        name: null,
        address: null,
        isShow: false
      },
      popupVisible: true,
      naviLine: {
        initLength: null,
        latestLength: null,
        lengthDefer: null,
        promptInfo: null,
        isShow: false
      },
      clickListener: null
    };
  },
  created: function() {
    this.username = this.getUserName();
  },
  mounted: function() {
    //this.$nextTick(() => {
    if (AMap) {
      this.mapInit();
    }
    //});
  },
  methods: {
    ...mapGetters([
      "getId",
      "getUserName",
      "getAcStoreMsg",
      "getOrderId",
      "getAcId"
    ]),
    mapInit() {
      this.id = this.getId();
      var map = new AMap.Map("AMapContainer", {
        resizeEnable: true,
        zoom: 11,
        center: [116.39, 39.9]
      });
      AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.OverView"], function() {
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
      });
      this.map = map;
      this.initRoute(); //初始化订单路线
      //定位
      map.plugin(
        "AMap.Geolocation",
        function() {
          var geolocation = new AMap.Geolocation({
            //noIpLocate:2, //PC禁止IP定位
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 1000, //超过1秒后停止定位，默认：无穷大
            maximumAge: 0, //定位结果缓存0毫秒，默认：0
            convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true, //显示定位按钮，默认：true
            buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(
            function(status, result) {
              this.myLocation = result.position;
            }.bind(this)
          );
          //geolocation.watchPosition();
          setInterval(
            function() {
              geolocation.getCurrentPosition();
            }.bind(this),
            300000
          ); //300秒

          AMap.event.addListener(geolocation, "complete", this.onComplete); //返回定位信息
          AMap.event.addListener(geolocation, "error", this.onError); //返回定位出错信息
        }.bind(this)
      );

      // //输入提示
      AMap.plugin(
        "AMap.Autocomplete",
        function() {
          //回调函数
          var auto = new AMap.Autocomplete({
            input: "searchContent"
          });
          AMap.event.addListener(
            auto,
            "select",
            function(result) {
              //TODO 针对选中的poi实现自己的功能
              this.destination.lng = result.poi.location.lng;
              this.destination.lat = result.poi.location.lat;
              //poi面板信息
              this.poiInfo.name = result.poi.name;
              if (result.poi.address.length != 0) {
                this.poiInfo.address = result.poi.address;
              }
              this.poiInfo.isShow = true;
              this.naviLine.isShow = false;
              //搜索地点 清空
              this.naviLine.initLength = 0;
              this.naviLine.latestLength = 0;
              this.naviLine.lengthDefer = 0;
              //清除上一次路线
              this.clearOverlays();
              var poiIcon = new AMap.Icon({
                image: poimarker, //24px*24px
                //icon可缺省，缺省时为默认的蓝色水滴图标，
                size: new AMap.Size(19, 31)
              });
              var marker = new AMap.Marker({
                icon: poiIcon,
                position: [result.poi.location.lng, result.poi.location.lat]
              });
              if (this.destinationMarker != null) {
                this.destinationMarker.setMap(null);
              }
              this.destinationMarker = marker;

              marker.setMap(map);
              map.setZoomAndCenter(14, [
                result.poi.location.lng,
                result.poi.location.lat
              ]);
            }.bind(this)
          );
        }.bind(this)
      );

      //添加障碍
      var bind = function() {
        remove(); //防止重复绑定
        this.clickListener = AMap.event.addListener(
          map,
          "click",
          function(e) {
            var circle = new AMap.Circle({
              center: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 圆心位置
              radius: 200, //半径
              strokeColor: "#F33", //线颜色
              strokeOpacity: 1, //线透明度
              strokeWeight: 3, //线粗细度
              fillColor: "#ee2200", //填充颜色
              fillOpacity: 0.35 //填充透明度
            });
            circle.setMap(map);
            this.avoidPointCircle.push(circle);
            var southWest = circle.getBounds().getSouthWest();
            var northEast = circle.getBounds().getNorthEast();
            var southEast = northEast.lng + "," + southWest.lat + ";";
            var northWest = southWest.lng + "," + northEast.lat + ";";
            this.avoidPoint =
              this.avoidPoint +
              southWest.lng +
              "," +
              southWest.lat +
              ";" +
              southEast +
              northEast.lng +
              "," +
              northEast.lat +
              ";" +
              northWest +
              "|";
            //信息窗口
            var infoWindow = new AMap.InfoWindow({
              content: "我在" + new Date().toLocaleTimeString() + "标记" //使用默认信息窗体框样式，显示信息内容
            });
            // infoWindow.open(this.map, [res.data[i].longitude,res.data[i].latitude]);
            circle.on(
              "click",
              function() {
                infoWindow.open(this.map, [
                  e.lnglat.getLng(),
                  e.lnglat.getLat()
                ]);
              }.bind(this)
            );
            AMap.event.removeListener(this.clickListener); //移除事件，以绑定时返回的对象作为参数
            //上传障碍点
            var data =
              "phone=" +
              this.id +
              "&longitude=" +
              this.avoidPointCircle[this.avoidPointCircle.length - 1]
                .getCenter()
                .getLng() +
              "&latitude=" +
              this.avoidPointCircle[this.avoidPointCircle.length - 1]
                .getCenter()
                .getLat() +
              "&detourdistance=" +
              0;
            var setting = {
              method: "post",
              url: "/getTruckObstacle"
            };
            axios.call(
              this,
              function(res) {
                if (res.code === 0) {
                  //	console.log(res)
                } else {
                  // console.log(res)
                }
              }.bind(this),
              {
                setting,
                data
              }
            );
          }.bind(this)
        );
      }.bind(this);
      var remove = function() {
        if (this.clickListener) {
          AMap.event.removeListener(this.clickListener); //移除事件，以绑定时返回的对象作为参数
        }
      }.bind(this);
      var button1 = document.getElementById("locatAvoid");
      var listener1 = AMap.event.addDomListener(button1, "click", bind); //给div绑定单击事件

      //获取障碍
      var data = null;
      var setting = {
        method: "get",
        url: "/putTruckObstacle"
      };
      axios.call(
        this,
        function(res) {
          if (res.code === 0) {
            this.initObstacle(res);
          } else {
            //this.$toast("无其它障碍物");
          }
        }.bind(this),
        {
          setting,
          data
        }
      );
    },
    submit() {
      var content = searchContent.value;
      this.map.plugin(
        "AMap.PlaceSearch",
        function() {
          var placeSearch = new AMap.PlaceSearch({
            //构造地点查询类
            pageSize: 5,
            pageIndex: 1
          });
          //关键字查询
          placeSearch.search(
            content,
            function(status, result) {
              //TODO:开发者使用result自己创建交互面板和地图展示
              if (result.info == "OK") {
                var poiIcon = new AMap.Icon({
                  image: poimarker, //24px*24px
                  //icon可缺省，缺省时为默认的蓝色水滴图标，
                  size: new AMap.Size(19, 31)
                });
                var marker = new AMap.Marker({
                  icon: poiIcon,
                  position: [
                    result.poiList.pois[0].location.lng,
                    result.poiList.pois[0].location.lat
                  ]
                });
                marker.setMap(this.map);
                this.map.setZoomAndCenter(14, [
                  result.poiList.pois[0].location.lng,
                  result.poiList.pois[0].location.lat
                ]);
                //poi面板信息
                this.poiInfo.name = result.poiList.pois[0].name;
                if (result.poiList.pois[0].address.length != 0) {
                  this.poiInfo.address = result.poiList.pois[0].address;
                }
                this.poiInfo.isShow = true;
                this.naviLine.isShow = false;
                this.destination.lng = result.poiList.pois[0].location.lng;
                this.destination.lat = result.poiList.pois[0].location.lat;
              }
            }.bind(this)
          );
        }.bind(this)
      );
    },
    search(startLocation, endLocation, callback) {
      //清除上一次路线
      this.clearOverlays();
      var start = startLocation.lng + "," + startLocation.lat;
      var end = endLocation.lng + "," + endLocation.lat;
      var avoidPoint = this.avoidPoint;
      // ------------起始、终点坐标
      var startIcon = new AMap.Icon({
        image: startPng, //24px*24px
        size: new AMap.Size(32, 32)
      });
      var startMarker = new AMap.Marker({
        icon: startIcon,
        position: [startLocation.lng, startLocation.lat]
      });
      startMarker.setMap(this.map);
      this.overlays.push(startMarker);
      var endIcon = new AMap.Icon({
        image: destinationPng, //24px*24px
        size: new AMap.Size(32, 32)
      });
      var endMarker = new AMap.Marker({
        icon: endIcon,
        position: [endLocation.lng, endLocation.lat]
      });
      endMarker.setMap(this.map);
      this.overlays.push(endMarker);
      // -----------起始、终点坐标
      //第一次请求 无障碍点时
      var str = { start: start, end: end, avoidPoint: "" };
      var data = JSON.stringify(str);
      var setting = {
        method: "post",
        url: "/getGaodeavoid"
      };
      axios.call(
        this,
        function(res) {
          if (res.status == 1) {
            this.naviLine.initLength = res.route.paths[0].distance;
          } else {
            // console.log(res)
          }
        }.bind(this),
        {
          setting,
          data
        }
      );

      //第二次请求
      var str = {
        start: start,
        end: end,
        avoidPoint: avoidPoint,
        avoidRoad: this.avoidRoad
      };
      var data = JSON.stringify(str);
      //var data="start="+start+"&end="+end+"&avoidPoint="+avoidPoint
      var setting = {
        method: "post",
        url: "/getGaodeavoid"
      };
      var destinationIcon = new AMap.Icon({
        image: destinationPng, //24px*24px
        //icon可缺省，缺省时为默认的蓝色水滴图标，
        size: new AMap.Size(32, 32)
      });
      axios.call(
        this,
        function(res) {
          if (res.status == 1) {
            this.naviLine.latestLength = res.route.paths[0].distance;
            this.addRoute(res);
            if (callback != undefined) {
              callback(this.naviLine.latestLength);
            }
            if (this.destinationMarker != null) {
              this.destinationMarker.setIcon(destinationIcon);
            }
          } else {
            // console.log(res)
          }
        }.bind(this),
        {
          setting,
          data
        }
      );
    },
    addRoute(data) {
      //新路线长度
      var newLength = 0;
      for (var i = 0; i < data.route.paths[0].steps.length; i++) {
        var linePoints = data.route.paths[0].steps[i].polyline;
        var path = linePoints.split(";"); //逗号是分隔符
        var lineArr2 = new Array();
        for (var j = 0; j < path.length; j++) {
          lineArr2[j] = new Array();
          var dd = path[j].split(",");
          lineArr2[j][0] = dd[0];
          lineArr2[j][1] = dd[1];
        }
        var polyline = new AMap.Polyline({
          path: lineArr2, //设置线覆盖物路径
          strokeColor: "#3366FF", //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 5, //线宽
          strokeStyle: "solid", //线样式
          strokeDasharray: [10, 5] //补充线样式
        });
        newLength = newLength + polyline.getLength();
        polyline.setMap(this.map);
        this.overlays.push(polyline);
      }

      this.map.setFitView();
      var overlaysList = this.map.getAllOverlays("circle");
      this.naviLine.promptInfo =
        "全程" + (this.naviLine.latestLength / 1000).toFixed(0) + "公里";
      if (overlaysList.length != 0) {
        this.naviLine.lengthDefer = (
          (this.naviLine.latestLength - this.naviLine.initLength) /
          1000
        ).toFixed(1);
        if (this.naviLine.lengthDefer > 0 && this.naviLine.initLength != 0) {
          //绕道距离为正数
          this.naviLine.promptInfo =
            "全程" +
            (this.naviLine.latestLength / 1000).toFixed(0) +
            "公里," +
            "需绕道行驶" +
            this.naviLine.lengthDefer +
            "公里";

          //上传障碍点！
          if (this.avoidPointCircle.length > 0) {
            var data =
              "phone=" +
              this.id +
              "&longitude=" +
              this.avoidPointCircle[this.avoidPointCircle.length - 1]
                .getCenter()
                .getLng() +
              "&latitude=" +
              this.avoidPointCircle[this.avoidPointCircle.length - 1]
                .getCenter()
                .getLat() +
              "&detourdistance=" +
              this.naviLine.lengthDefer;
            var setting = {
              method: "post",
              url: "/getTruckObstacle"
            };
            axios.call(
              this,
              function(res) {
                if (res.code === 0) {
                  //	console.log(res)
                } else {
                  // console.log(res)
                }
              }.bind(this),
              {
                setting,
                data
              }
            );
          }

          //距离变短时
        } else if (this.naviLine.lengthDefer < 0) {
          // this.naviLine.promptInfo="全程"+(this.naviLine.latestLength/1000).toFixed(0)+"公里,"+"节省路线"+(-this.naviLine.lengthDefer)+"公里";
        }
        // console.log("无障碍点时:"+this.naviLine.initLength+","+"有障碍点时"+this.naviLine.latestLength+","+"差值"+this.naviLine.lengthDefer)
      }
      this.naviLine.isShow = true;
    },
    clearOverlays() {
      for (var i = 0; i < this.overlays.length; i++) {
        this.overlays[i].setMap(null);
      }
      this.overlays.splice(0, this.overlays.length); //清空数组
    },
    addAvoid() {
      MessageBox.prompt(" ", {
        title: "请输入避让道路名",
        cancelButtonText: "不，我要在地图上选取"
      }).then(
        function(action) {
          //确认
          this.avoidRoad = action.value;
          AMap.event.removeListener(this.clickListener); //移除事件，以绑定时返回的对象作为参数
        }.bind(this),
        function(action) {
          //取消
        }.bind(this)
      );
    },
    clearAvoid() {
      for (var i = 0; i < this.avoidPointCircle.length; i++) {
        this.avoidPointCircle[i].setMap(null);
      }
      var data = {
		phone: this.$store.state.user.userid
	  };
      var setting = {
        method: "POST",
        url: "/removeHazardPoint",
      };
      axios.call(
        this,
        res => {
          this.removeHazardCallback(res);
        },
        { setting: setting, data: data }
      );
	},
	removeHazardCallback: function (res) {
      if(res.code === 0){
		  // console.log(res)
      }else{
        // console.log(0)
      }
    },
    onComplete(result) {
      if (result.info == "SUCCESS") {
        this.myLocation = result.position;
        var data =
          "phone=" +
          this.id +
          "&longitude=" +
          this.myLocation.lng +
          "&latitude=" +
          this.myLocation.lat;
        var setting = {
          method: "post",
          url: "/getTruckPosition"
        };
        axios.call(
          this,
          function(res) {
            if (res.code === 0) {
              //	console.log(res)
            } else {
              // console.log(res)
            }
          }.bind(this),
          {
            setting,
            data
          }
        );
      }
    },
    onError(result) {
      Toast({
        message: "暂未获取您的位置信息",
        position: "bottom"
      });
    },
    initObstacle(res) {
      for (var i = 0; i < res.data.length; i++) {
        (function(i) {
          var circle = new AMap.Circle({
            center: new AMap.LngLat(
              res.data[i].longitude,
              res.data[i].latitude
            ), // 圆心位置
            radius: 200, //半径
            strokeColor: "#F33", //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 3, //线粗细度
            fillColor: "#ee2200", //填充颜色
            fillOpacity: 0.35 //填充透明度
          });
          circle.setMap(this.map);
          var southWest = circle.getBounds().getSouthWest();
          var northEast = circle.getBounds().getNorthEast();
          var southEast = northEast.lng + "," + southWest.lat + ";";
          var northWest = southWest.lng + "," + northEast.lat + ";";
          this.avoidPoint =
            this.avoidPoint +
            southWest.lng +
            "," +
            southWest.lat +
            ";" +
            southEast +
            northEast.lng +
            "," +
            northEast.lat +
            ";" +
            northWest +
            "|";

          var date = res.data[i].positiontime;
          var infoWindow = new AMap.InfoWindow({
            content:
              res.data[i].name +
              "在" +
              date.substring(date.length - 8, date.length) +
              "标记" //使用默认信息窗体框样式，显示信息内容
          });
          // infoWindow.open(this.map, [res.data[i].longitude,res.data[i].latitude]);
          circle.on(
            "click",
            function() {
              infoWindow.open(this.map, [
                res.data[i].longitude,
                res.data[i].latitude
              ]);
            }.bind(this)
          );
        }.bind(this)(i)); //调用时参数
      }
    },
    initRoute() {
      var freightId = this.getOrderId();
      /*
		    	var setting = {
			            method: 'POST',
			            url: '/getAlreadyOrderInfo'
			          };
			      var data = {
			            phone: this.getId()
			          };
			      axios((res) => {
			        if(res.code === 0) {
			           var msg = res.data;
			           orderid=msg.id;      
			        }
			      }, {setting, data}); */
      var start = {
        lng: null,
        lat: null
      };
      var setting = {
        method: "GET",
        url: "/getTruckOrderDetailedTwo/" + freightId
      };
      axios(
        res => {
          if (res.code === 0) {
            var msg = res.data;
            if (msg != null) {
              for (var i = 0; i < msg.length; i++) {
                (function(i) {
                  if (
                    msg[i].factorylongitude != "暂无数据" &&
                    msg[i].factorylatitude != "暂无数据" &&
                    msg[i].bournlongitude != "暂无数据" &&
                    msg[i].bournlatitude != "暂无数据"
                  ) {
                    var startlnglat = new AMap.LngLat(
                      msg[i].factorylongitude,
                      msg[i].factorylatitude
                    );
                    var endlnglat = new AMap.LngLat(
                      msg[i].bournlongitude,
                      msg[i].bournlatitude
                    );
                    var orderid = msg[i].orderid;
                    var lnglatArr = new Array();
                    lnglatArr[0] = startlnglat;
                    lnglatArr[1] = endlnglat;
                    new AMap.convertFrom(
                      lnglatArr,
                      "baidu",
                      function(status, result) {
                        start.lng = result.locations[0].lng;
                        start.lat = result.locations[0].lat;
                        this.destination.lng = result.locations[1].lng;
                        this.destination.lat = result.locations[1].lat;
                        this.search(
                          start,
                          this.destination,
                          function(kilometre) {
                            this.sendKilometers(orderid, freightId, kilometre);
                          }.bind(this)
                        );
                      }.bind(this)
                    );

                    //poi面板信息
                    this.poiInfo.name = msg[i].bourn;
                    this.poiInfo.isShow = true;
                    this.naviLine.isShow = false;
                    if (this.destinationMarker != null) {
                      this.destinationMarker.setMap(null);
                    }
                  }
                }.bind(this)(i));
              }
            }
          } else {
            if (res.code === 401) {
            }
          }
        },
        { setting: setting }
      );
    },
    sendKilometers(orderid, freightId, kilometre) {
      var setting = {
        method: "POST",
        url: "/getPhoneKilometre"
      };
      var data = {
        orderid: orderid,
        freightId: freightId,
        kilometre: kilometre
      };
      axios(
        res => {
          if (res.code === 0) {
          }
        },
        { setting, data }
      );
    }
  }
};
</script>

<style>
.searchbox {
  height: 32px;
  font-size: 0.9375rem;
  background: #fff;
  border-radius: 4px;
  z-index: 99999;
}
#AMapContainer {
  /* 	position: relative;
    bottom: 0;
    right: 0;
    left: 0;*/
  height: calc(100% - 42px);
}
.searchbox_bar {
  margin: 0px;
  padding: 0 10px 10px 10px;
  background: rgb(73, 80, 96);
}
.C_commonInput {
  width: 88%;
  padding: 0 0px 0 7px;
  margin: 0px;
  height: 32px;
  background: #fff;
  font-size: 0.9375rem;
  /*color: rgb(110,110,110);*/
}
.button {
  height: 32px;
  line-height: 31px;
  width: 42px;
  background: url(../../assets/images/mysearch.png) no-repeat center;
  background-size: 25px 25px;
  color: #ffffff;
  border: none;
  display: inline;
  font-size: 0.75rem;
  position: absolute;
  right: 10px;
  border-radius: 0px 3px 3px 0px;
}
.mycontrollocat {
  position: absolute;
  width: 35px;
  height: 35px;
  right: 10px;
  background: url(../../assets/images/obstacle.png) no-repeat 5px 5px;
  background-size: 30px 30px;
  z-index: 99999;
}
.mycontrolclear {
  position: absolute;
  top: 120px;
  width: 35px;
  height: 35px;
  right: 10px;
  background: url(../../assets/images/clear.png) no-repeat 5px 5px;
  background-size: 30px 30px;
  z-index: 99999;
}
.info {
  border-radius: 10px;
  position: absolute;
  width: 70%;
  height: 110px;
  bottom: 32px;
  background: #fff;
  z-index: 1000;
  left: 15%;
}
.placeinfo {
  height: 70px;
}
.info .title {
  display: block;
  height: 1em;
  line-height: 1em;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-left: 10px;
  margin-top: 5px;
  margin-bottom: 10px;
}
.address {
  display: block;
  height: 1rem;
  line-height: 1em;
  overflow: hidden;
  font-size: 13px;
  color: #999;
  margin-left: 10px;
  margin-bottom: 5px;
}
.bottombutton {
  bottom: 32px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-top: 1px solid #e8e8e8;
  color: #666;
  background: url(../../assets/images/route.png) no-repeat 30% 5px;
  background-size: 26px 22px;
}
.searchbox_bar input {
  outline-style: none;
}
.searchbox_bar input {
  margin: 0;
  padding-left: 5px;
  -webkit-appearance: none;
  border-style: none;
}

.searchbox_bar button,
input {
  line-height: normal;
}
.searchbox_bar button,
input {
  font-size: 100%;
  margin: 0;
  vertical-align: baseline;
}
</style>
